//
//  TLPaintView.m
//  KidReading
//
//  Created by telen on 16/5/16.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "TLPaintView.h"

@implementation TLPaintModel
@end

@interface TLPaintView()
//声明贝塞尔曲线
@property(nonatomic, strong) UIBezierPath *bezier;
@property(nonatomic, strong) UIBezierPath *bezier_load;
//存储Undo出来的线条
@property(nonatomic, strong) NSMutableArray *cancleArray;
@end

@implementation TLPaintView
{
    CGPoint ppoint;//前一点
    NSMutableArray* marr_points;
}

-(void)initPaintView
{
    self.paintModel = [[TLPaintModel alloc] init];
    self.paintModel.color = [UIColor redColor];
    self.paintModel.lineWidth = 5;
    self.drawLineRatio = 1;
    self.allLine = [NSMutableArray arrayWithCapacity:0];
    self.cancleArray = [NSMutableArray arrayWithCapacity:0];
}

-(void)backImage
{
    if (self.allLine.count > 0)
    {
        NSInteger index = self.allLine.count - 1;
        [self.cancleArray addObject:self.allLine[index]];
        [self.allLine removeObjectAtIndex:index];
        [self setNeedsDisplay
         ];
    }
}

-(void)forwardImage
{
    if (self.cancleArray.count > 0)
    {
        NSInteger index = self.cancleArray.count - 1;
        [self.allLine addObject:self.cancleArray[index]];
        [self.cancleArray removeObjectAtIndex:index];
        [self setNeedsDisplay];
    }
}

- (void)clear
{
    [self.allLine removeAllObjects];
    [self.cancleArray removeAllObjects];
    [self setNeedsDisplay];
}

- (void)delLineNearPoint:(CGPoint)point
{
    //TODO: 未完
}

- (void)paintModelList:(NSArray<TLPaintModel *> *)modelList
{
    __block CGPoint pt;
    for (int i=0; i<modelList.count; i++) {
        TLPaintModel* paintModel = modelList[i];
        self.bezier_load = [UIBezierPath bezierPath];
        //把每条线存入字典中
        NSMutableDictionary *tempDic = [NSMutableDictionary new];
        if (paintModel.isEarser) {
            [tempDic setObject:@"" forKey:@"earser"];
        }
        if(paintModel.color)
            [tempDic setObject:paintModel.color forKey:@"color"];
        else
            NSLog(@"Error: lineColor == null");
        
        [tempDic setObject:[NSNumber numberWithFloat:paintModel.lineWidth] forKey:@"lineWidth"];
        [tempDic setObject:self.bezier_load forKey:@"line"];
        //把线加入数组中
        [self.allLine addObject:tempDic];
        __block CGFloat mx =0, my = 0, x, y;
        [paintModel.points enumerateObjectsUsingBlock:^(NSValue*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            pt = [obj CGPointValue];
            x = pt.x;
            y = pt.y;
            if (mx == my && mx == 0) {
                //把刚触摸的点设置为bezier的起点
                [self.bezier_load moveToPoint:CGPointMake(x, y)];
            }else{
                [self.bezier_load addQuadCurveToPoint:CGPointMake((x+mx)*0.5, (y+my)*0.5) controlPoint:CGPointMake(mx, my)];
            }
            mx = x;
            my = y;
        }];
        //NSLog(@"%@",paintModel.createTime);
    }
    [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:NO];
}

#pragma mark-
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    //
    //对之前的线的一个重绘过程
    NSArray* arr = [NSArray arrayWithArray:self.allLine];
    NSDictionary *tempDic = nil;
    UIColor *color = nil;
    CGFloat width;
    UIBezierPath *path;
    id earser = nil;
    for (int i = 0; i < arr.count; i++ )
    {
        tempDic = arr[i];
        color = tempDic[@"color"];
        width = [tempDic[@"lineWidth"] floatValue]*self.drawLineRatio;
        path = tempDic[@"line"];
        earser = tempDic[@"earser"];
        if (earser) {
            CGContextSetBlendMode(context, kCGBlendModeClear);
        }else{
            CGContextSetBlendMode(context, kCGBlendModeNormal);
        }
        
        [color setStroke];
        [path setLineWidth:width];
        [path setLineCapStyle:kCGLineCapRound];
        [path setLineJoinStyle:kCGLineJoinRound];
        [path stroke];
    }
    
}

#pragma mark-
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //获取触摸的点
    UITouch *myTouche = [touches anyObject];
    CGPoint point = [myTouche locationInView:self];
    
    //点击删除模式
    if (_isClickedToDelModel) {
        [self delLineNearPoint:point];
        return;
    }
    //新建贝塞斯曲线
    self.bezier = [UIBezierPath bezierPath];
    
    //把刚触摸的点设置为bezier的起点
    [self.bezier moveToPoint:point];
    
    //把每条线存入字典中
    NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] initWithCapacity:3];
    [tempDic setObject:self.paintModel.color forKey:@"color"];
    [tempDic setObject:[NSNumber numberWithFloat:self.paintModel.lineWidth] forKey:@"lineWidth"];
    [tempDic setObject:self.bezier forKey:@"line"];
    if (_isEarser) {
        [tempDic setObject:@"" forKey:@"earser"];
    }
    
    //把线加入数组中
    [self.allLine addObject:tempDic];
    
    //
    ppoint = point;
    //
    marr_points = [NSMutableArray new];
    [marr_points addObject:[NSValue valueWithCGPoint:point]];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_isClickedToDelModel) {
        return;
    }
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    
    float  TOUCH_TOLERANCE = 2.f;
    float dx = fabs(point.x - ppoint.x);
    float dy = fabs(point.y - ppoint.y);
    
    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
        
        //[self.bezier addLineToPoint:point];
        [self.bezier addQuadCurveToPoint:CGPointMake((point.x+ppoint.x)*0.5, (point.y+ppoint.y)*0.5) controlPoint:ppoint];
        ppoint = point;
        [marr_points addObject:[NSValue valueWithCGPoint:point]];
        
        //重绘界面
        [self setNeedsDisplay];
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (marr_points && marr_points.count > 1 && self.didAddPaintModel) {
        TLPaintModel* paintModel = [[TLPaintModel alloc] init];
        paintModel.color = self.paintModel.color;
        paintModel.lineWidth = self.paintModel.lineWidth;
        paintModel.isEarser = self.isEarser;
        paintModel.points = marr_points;
        paintModel.createTime = [NSDate date];
        self.didAddPaintModel(paintModel);
    }
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self touchesEnded:touches withEvent:event];
}

#pragma mark-
- (void)readTestData
{
    NSString* path = [[NSBundle mainBundle] pathForResource:@"testPaint" ofType:@"txt"];
    NSData* data = [NSData dataWithContentsOfFile:path];
    NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if (dict) {
        NSArray* strokeList = dict[@"strokeList"];
        for (NSDictionary* stoke in strokeList) {
            NSArray* mPoints = stoke[@"mPoints"];
            self.bezier = [UIBezierPath bezierPath];
            //把每条线存入字典中
            NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] initWithCapacity:3];
            [tempDic setObject:self.paintModel.color forKey:@"color"];
            [tempDic setObject:[NSNumber numberWithFloat:self.paintModel.lineWidth] forKey:@"lineWidth"];
            [tempDic setObject:self.bezier forKey:@"line"];
            //把线加入数组中
            [self.allLine addObject:tempDic];
            __block CGFloat mx =0, my = 0, x, y;
            [mPoints enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                x = [obj[@"x"] floatValue];
                y = [obj[@"y"] floatValue];
                if (mx == my && mx == 0) {
                    //把刚触摸的点设置为bezier的起点
                    [self.bezier moveToPoint:CGPointMake(x, y)];
                }else{
                    [self.bezier addQuadCurveToPoint:CGPointMake((x+mx)*0.5, (y+my)*0.5) controlPoint:CGPointMake(mx, my)];
                }
                mx = x;
                my = y;
            }];
        }
    }
    NSLog(@"%@",self.allLine);
}

@end
